import { reactive, toRefs, getCurrentInstance, h } from "vue"
// ant design
import { message } from "ant-design-vue"
// api
import { userList, userDelete, userStaus } from "@/api/user"

export function useUser() {
    // proxy
    const { proxy } = getCurrentInstance()
    // state
    const state = reactive({
        dataList: [],
    })

    /**
     * 获取列表
     */
    const useGetUserList = (params) => {
        return new Promise((resolve, reject) => {
            userList(params).then(res => {
                state.dataList = res?.content?.data
                resolve(res)
            })
        })
    }

    /**
     * 删除
     */
    const useDeleteUser = (row) => {
        proxy.$confirm({
            title: "确认删除？",
            content: h('span', { class: "color-error" }, '删除后该用户ID将在本系统中将无法登录使用并删除，',
                     h('span', { class: "color-9"}, '请谨慎操作！')
                    ),
            okAsync: () => {
              return new Promise((resolve, reject) => { // then，catch
                userDelete({id: row.member_id}).then(() => {
                  message.success('删除成功')
                  useGetUserList()
                  resolve()
                }).catch(() => {
                  reject()
                })
              })
            }
          })
    }

    /**
     * 更新状态
     */
    const useStatusUser = (params) => {
        const content = params.status 
                  ? 
                  h('span', { class: "color-error" }, '删除后该用户ID将在本系统中将无法登录使用并删除，',
                    h('span', { class: "color-9"}, '请谨慎操作！')
                  ) 
                  : h('span', { class: "color-error" }, '启用后用户在本系统的权限将一并重新开启。')
        return new Promise((resolveSwitch, rejectSwitch) => {
            proxy.$confirm({
                title: params.status ? "确认禁用？" : "确认启用？",
                content,
                okAsync: () => {
                    return new Promise((resolve, reject) => { // then，catch
                    const req = {
                        id: params.member_id,
                        status: params.status ? 0 : 1
                    }
                    userStaus(req).then((res) => {
                        message.success(res?.msg)
                        resolve()
                        resolveSwitch()
                    }).catch(() => {
                        reject()
                    })
                })
            },
            cancelAsync: () => {
                rejectSwitch()
            }
            })
        })
    }

    return {
        ...toRefs(state),
        useGetUserList,
        useDeleteUser,
        useStatusUser
    }
}